/*
 * Selector.java
 *
 * Created on 9 maj 2007, 18:52
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package pl.krakow.ae.knp.wikiboard.gui.tools.transformers;

import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.util.Iterator;
import pl.krakow.ae.knp.wikiboard.gui.board.Board;
import pl.krakow.ae.knp.wikiboard.gui.board.BoardEvent;
import pl.krakow.ae.knp.wikiboard.gui.drawables.Drawable;

/**
 *
 * @author m
 */
public class Selector extends Transformer
{
    Drawable drawable, newDrawable, selected;
    Point2D startPoint;
    
    /** Creates a new instance of Selector */
    public Selector()
    {
    }
    
    public BoardEvent createEvent()
    { return new BoardEvent(drawable, newDrawable); }
    
    public void mousePressed(MouseEvent event, Graphics2D g)
    {
        if (selected != null)
            selected.unselect();
        
        Point2D point = event.getPoint();
        startPoint = point;
        Iterator<Drawable> it = Board.drawablesList.iterator();
        while(it.hasNext())
        {
            Drawable d = it.next();
            if (d.contains(point))
            {
                drawable = d;
                newDrawable = drawable.clone();
                newDrawable.select();
                selected = newDrawable;
            }
        }
        
        
    }
    
    public void mouseDragged(MouseEvent event, Graphics2D g)
    {
        Point2D point = event.getPoint();
        if (drawable != null)
        {
            double dX = point.getX() - startPoint.getX();
            double dY = point.getY() - startPoint.getY();
            startPoint = point;
            newDrawable.draw(g, true);
            newDrawable.move(dX, dY);
            newDrawable.draw(g, true);
        }
    }
    
    public void mouseReleased(MouseEvent event, Graphics2D g)
    {
        if (newDrawable != null)
        {
            newDrawable.draw(g, false);
            BoardEvent e = createEvent();
            processBoardEvent(e);
            startPoint = null;
            drawable = null;
            newDrawable = null;
        }
        
    }
    
    public Drawable getDrawable()
    { return drawable; }
    
    
}
